package guru.springframework.controllers;

import guru.springframework.domain.Product;
import guru.springframework.domain.ProductB;
import guru.springframework.dto.MockGetRequest;
import guru.springframework.dto.MockGetResponse;
import guru.springframework.services.HttpService;
import guru.springframework.services.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;




@Slf4j
@Controller
public class ProductController {

    private ProductService productService;
    private HttpService httpService;

    @Autowired
    public void setService(HttpService httpService,ProductService productService) {
        this.httpService = httpService;
        this.productService = productService;
    }

    @RequestMapping(value = "/products", method = RequestMethod.GET)
    public String list( Model model) {
        model.addAttribute("products", productService.listAllProducts());
        log.info("Returning rpoducts:");
        return "products";
    }

    @RequestMapping("product/{id}")
    public String showProduct(@PathVariable Integer id, Model model) {
        model.addAttribute("product", productService.getProductById(id));
        return "productshow";
    }

    @RequestMapping("product/edit/{id}")
    public String edit(@PathVariable Integer id, Model model) {
        model.addAttribute("product", productService.getProductById(id));
        return "productform";
    }

    @RequestMapping("product/delete/{id}")
    public String delete(@PathVariable Integer id) {
        productService.deleteProductById(id);
        return "redirect:/products/";
    }


    @GetMapping(value = "product/sendGet/{id}")
    public String getTheProducts(@PathVariable Integer id,Model model) {
        model.addAttribute("result", httpService.getProductsByGet(id));
        model.addAttribute("products", productService.listAllProducts());
        return "products";
    }

    @PostMapping("product/mockGet")
    @ResponseBody
    public MockGetResponse getResponse(@RequestBody MockGetRequest mockGetRequest){
        MockGetResponse getResponse = new MockGetResponse();
        getResponse.setMessage(String.format("使用" + mockGetRequest.getMethod() + "方法调用:" + mockGetRequest.getUrl()));
        return getResponse;
    }

    @RequestMapping("product/new")
    public String newProduct(Model model) {
        model.addAttribute("product", new Product());
        return "productform";
    }

    @RequestMapping(value = "product", method = RequestMethod.POST)
    public String saveProduct(ProductB product) {

        productService.saveProduct(product);

        return "redirect:/product/" + product.getId();
    }

}
